#!/bin/sh -e

checkargs() { test $# -eq $1; }

filter='label=org.cockpit-project.container=unit-tests'
defaultargs='-it'
defaultcmd='/bin/bash'
args=''
id=''

while test $# -gt 0; do
  case "$1" in
    --docker) docker="docker";;
    --podman) docker="podman";;
    --root) args="$args -uroot";;
    --id=*) id="${1#--id=}";;
    -it) args="$args -it"; defaultargs='';;
    --) break;;
    --*) printf 'usage: %s [--root] [--id=<id>] [-it] cmd...\n' "$0"; exit 1;;
    *) break;;
  esac
  shift
done

if test -z "${docker:=$(which podman || which docker || true)}"; then
  echo 'Neither podman nor docker are installed'
  exit 1
fi

if [ -z "$id" ]; then
  id="$(${docker} ps -qf "${filter}")"

  if checkargs 2 $id; then :
  elif checkargs 1 $id; then
    echo 'Cannot find any running cockpit/unit-tests container'
    exit 1
  else
    echo 'More than one running cockpit-unit/tests container:'
    echo
    ${docker} ps -f "${filter}" | sed -e 's/^/  /'
    echo
    echo 'Use --id= to specify which one.'
    exit 1
  fi
fi

if test $# -eq 0; then
  args="$args $defaultargs"
  set -- $defaultcmd
fi


set -ex
exec ${docker} exec ${args} -- "${id}" /entrypoint "$@"
